<?php namespace Common\Model;
use Hdphp\Model\Model;
class Cate extends Model{
    //指定分类表
    protected $table='category';
    //指定自动验证信息
    protected $validate=array(
        //array(字段名，验证方法，错误信息，验证条件，验证事件）
        array('cname','required','类型名称不能为空',3,3)
    );
    //分类添加
    public function store(){
        if($this->create()){
            $this->add();
            return true;
        }
        return false;
    }
    //分类编辑
    public function edit(){
        if($this->create()){

            $this->save();
            return true;
        }
        return false;
    }
    //获得除了自己和自己子集的分类
    public function getNoMy($cid){
        $cids=$this->getSon($this->get(),$cid);
        $cids[]=$cid;
        //排除自己和自己子集的数据
        $w="cid NOT IN(".implode(',',$cids).")";
        return $this->where($w)->get();
    }
    //获得自己的子集
    public function getSon($data,$cid){
        $temp=array();
        foreach($data as $d){
            if($d['pid']==$cid){
                $temp[]=$d['cid'];
                //递归获得到所有的自己
                $temp=array_merge($temp,$this->getSon($data,$d['cid']));
            }
        }
        return $temp;
    }
    //编辑分类类型时，同时改变子集的类型
    public function changeSon($cid){
        $cids=$this->getSon($this->get(),$cid);
        $cids[]=$cid;

        foreach ($cids as $c){
            $tid=$this->where("cid=$c")->pluck('type_typeid');
            $this->where("cid={$c}")->save(array('type_typeid'=>"{$tid}"));
        }
    }
    //获得当前cid对应的所有父集
    public function getFather($data,$cid){
        $temp=[];
        foreach($data as $d){
            $pid=$this->where("cid={$cid}")->pluck('pid');
            if($d['cid']==$pid){
                $temp[]=$d['cid'];
                $temp=array_merge($temp,$this->getFather($data,$d['cid']));
            }
        }
        return $temp;
    }
}
